package com.mxw.算法之美.a12搜索;

import com.mxw.算法之美.a11图.a01Graph;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * @author Administrator
 * @create 2024/7/31 14:40
 */
public class a02深度搜索DFS {

    /**
     * 试探性递归搜索
     */

    /**
     * 寻找从s到t的最短路径
     */

    a01Graph graph = new a01Graph(10);

    int v = graph.getV();
    LinkedList<Integer>[] adj = graph.getAdj();

    /**
     * 全局变量，当找到终止顶点后，不再递归地继续查找
     */
    boolean found = false;

    public void dfs(int s, int t) {


        found = false;

        // 备忘录
        boolean[] visited = new boolean[v];

        // 记录搜索路径 通过顶点2的邻接表访问到顶点3，prev[3] = 2
        int[] prev = new int[v];
        Arrays.fill(prev, -1);

        recursiveDfs(s, t, visited, prev);

    }

    public void recursiveDfs(int w, int t, boolean[] visited, int[] prev) {
        if (found == true) {
            return;
        }
        visited[w] = true;

        // 找到t
        if (w == t) {
            found = true;
            return;
        }

        // 遍历w的邻接表
        for (int i = 0; i < adj[w].size(); i++) {
            int q = adj[w].get(i);
            if (!visited[q]) {
                prev[q] = w;
                recursiveDfs(q, t, visited, prev);
            }
        }
    }
}
